package com.bluesky.trace;

import cn.hutool.core.util.IdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(urlPatterns = "/**", filterName = "TraceFilter")
public class TraceFilter extends OncePerRequestFilter {

    public static Logger logger = LoggerFactory.getLogger(TraceFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String traceId = IdUtil.fastSimpleUUID();
        TraceUtils.setTraceId(traceId);

        long st = System.currentTimeMillis();
        try{
            filterChain.doFilter(request, response);
        }finally {
            long et = System.currentTimeMillis();
            logger.info("请求地址:{},接口耗时：{}ms",request.getRequestURL().toString(),et-st);
            TraceUtils.removeTraceId();
        }
    }
}
